﻿using TbShop.Web.Helpers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TbShop;
using TbShop.Web.Infrastructure;
using System.IO;
using TbShop.Web.Infrastructure.FromExtend;
using TbShop.Business.Components;
using TbShop.Entity;
using HeinQi.Framework.Common.Caching;
using System.Threading.Tasks;
using HeinQi.Framework.Common;
using System.Net;
using System.Net.Sockets;
using Microsoft.AspNet.Identity;
using TbShop.Web.Infrastructure.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using TbShop.Web.Areas.Admin.Models;
using Microsoft.Owin.Security;

namespace TbShop.Web.Areas.Admin.Controllers
{
    [Authorize]
    public class AccountController : BaseController
    {
        public AccountController()
            : this(new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext())))
        {

        }

        public AccountController(UserManager<ApplicationUser> userManager)
        {
            UserManager = userManager;
        }

        public UserManager<ApplicationUser> UserManager { get; private set; }


        private ServiceComponents<LoginLog> logBC = new ServiceComponents<LoginLog>();
        /// <summary>
        /// 登录页面
        /// </summary>
        /// <param name="returnUrl"></param>
        /// <returns></returns>
        [AllowAnonymous]
        public ActionResult Login(string returnUrl)
        {
            CacheFactory.Clear();
            ViewBag.ReturnUrl = returnUrl;
            return View();
        }
        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="model"></param>
        /// <param name="returnUrl"></param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                var user = await UserManager.FindAsync(model.UserName, model.Password);
                if (user != null)
                {
                    if (user.LockoutEnabled && user.LockoutEndDateUtc.HasValue && user.LockoutEndDateUtc.Value > DateTime.Now)
                    {
                        ModelState.AddModelError("", "账户已被管理员锁定。");
                    }
                    else
                    {
                        Session.Clear();
                        SessionHelper.Set(StaticWords.SessionUserIdKey, user.Id);
                        SessionHelper.Set(StaticWords.SessionUserNameKey, user.UserName);
                        SessionHelper.Set(StaticWords.SessionRoleIdKey, user.RoleId);
                        SendMessage("登录成功！");
                        await SignInAsync(user, model.RememberMe);
                        var log = new LoginLog();
                        var data = logBC.GetAll().Where(a => a.AdminId == user.Id);
                        if (data.Any())
                        {
                            log = data.FirstOrDefault();
                        }
                        else
                        {
                            log.AdminId = user.Id;
                        }
                        log.LastLoginTime = DateTime.Now;
                        log.LastLoginIP = GetLocalIP();
                        log.LoginCount++;
                        log.FillEntity(user.UserName);
                        logBC.Save(log);
                        return RedirectToLocal(returnUrl);
                    }
                }
                else
                {
                    ModelState.AddModelError("", "用户名密码不正确。");
                }
            }
            return View(model);
        }
        private IAuthenticationManager AuthenticationManager
        {
            get
            {
                return HttpContext.GetOwinContext().Authentication;
            }
        }

        private async Task SignInAsync(ApplicationUser user, bool isPersistent)
        {
            AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
            var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
            AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);
            SessionHelper.Set(StaticWords.SessionUserIdKey, user.Id);
        }


        private ActionResult RedirectToLocal(string returnUrl)
        {
            if (Url.IsLocalUrl(returnUrl))
            {
                return Redirect(returnUrl);
            }
            else
            {
                return RedirectToAction("Index", "Dashboard");
            }
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult LogOff()
        {
            return RedirectToAction("Index", "Home");
        }

        /// <summary>  
        /// 获取当前使用的IP  
        /// </summary>  
        /// <returns></returns>  
        public static string GetLocalIP()
        {
            try
            {
                string HostName = Dns.GetHostName(); //得到主机名
                IPHostEntry IpEntry = Dns.GetHostEntry(HostName);
                for (int i = 0; i < IpEntry.AddressList.Length; i++)
                {
                    //从IP地址列表中筛选出IPv4类型的IP地址
                    //AddressFamily.InterNetwork表示此IP为IPv4,
                    //AddressFamily.InterNetworkV6表示此地址为IPv6类型
                    if (IpEntry.AddressList[i].AddressFamily == AddressFamily.InterNetwork)
                    {
                        return IpEntry.AddressList[i].ToString();
                    }
                }
                return "";
            }
            catch (Exception ex)
            {
                return "";
            }
        }
    }
}